﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

using Common.Library;
using OnlineVideos.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.ComponentModel;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using OnlineVideos.UI;

namespace VideoMix.Views
{
    public partial class MixVideosPopupPage : PhoneApplicationPage
    {
        #region Global declaration
        public static bool StartPreview = false;
        List<PlayListTable> listtable = new List<PlayListTable>();
        public static bool endtimestatus = false;
        public static bool StartTimeStatus = false;
        List<PlayListTable> previewlist = new List<PlayListTable>();
        TimeSpan starttime = default(TimeSpan);
        TimeSpan endtime = default(TimeSpan);
        TimeSpan SaveStartTime = default(TimeSpan);
        TimeSpan SaveEndTime = default(TimeSpan);
        TimelineMarker marker = new TimelineMarker(); 
        public static int previewid = 0;
        int PreviewPlaylistIndex = 0;
        public static bool positionchangedforpreview = false;
        public static bool markerstatus = false;
        public static bool deletebookmark = false;
        #endregion

        public MixVideosPopupPage()
        {
            InitializeComponent();
            Loaded += MixVideosPopupPage_Loaded;
        }

        #region Methods
        public void youtub()
        {
            try
            {


                if (!string.IsNullOrEmpty(AppSettings.YoutubeUri))
                {
                    Uri source = new Uri(AppSettings.YoutubeUri, UriKind.RelativeOrAbsolute);
                    videoMediaElement.Source = source;
                    if (StartPreview == true)
                    {
                        starttime = TimeSpan.Parse((previewlist.Cast<PlayListTable>().ElementAt(PreviewPlaylistIndex).StartTime));
                        endtime = TimeSpan.Parse((previewlist.Cast<PlayListTable>().ElementAt(PreviewPlaylistIndex).EndTime));
                        videoMediaElement.Play();
                        positionchangedforpreview = true;
                        if (PreviewPlaylistIndex == previewlist.Count)
                        {
                            PreviewPlaylistIndex = 0;
                        }


                    }
                    PreviewPlaylistIndex++;
                }
            }
            catch (Exception ex)
            {

            }
        }

        public void videoplaylist()
        {
            try
            {
                if (StartPreview == true)
                {
                    string url = previewlist.Cast<PlayListTable>().ElementAt(PreviewPlaylistIndex).LinkUrl;
                    AppSettings.LinkUrl = string.Empty;
                    AppSettings.YoutubeUri = string.Empty;
                    AppSettings.LinkUrl = url;
                }
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                wc.DownloadStringAsync(new Uri(AppSettings.LinkUrl.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "").Replace("http://www.youtube.com/v/", "http://www.youtube.com/watch?v=")));
                wc.DownloadStringCompleted += wc_DownloadStringCompleted;
            }
            catch (Exception ex)
            {


            }
        }

        private void StartpositionForBookmark()
        {
            try
            {

                SaveStartTime = videoMediaElement.Position;
                if (StartTimeStatus == false)
                {
                    PlayListTable list = new PlayListTable();
                    list.StartTime = "00:00:00";
                    list.EndTime = "00:00:00";
                    list.BookMarkNo = previewid + ".";
                    listtable.Add(list);
                    StartTimeStatus = true;
                }
                int count = listtable.Count;
                var item = listtable.ElementAt(count - 1);
                item.StartTime = SaveStartTime.ToString().Split('.')[0];
                item.ID = previewid;
                try
                {
                  
                  listitems.Items.Clear();
                         
                }
                catch (Exception ex)
                {
                    
                    
                }
              
                foreach (PlayListTable itm in listtable)
                {
                    listitems.Items.Add(itm);
                }

                endtimestatus = true;
            }
            catch (Exception ex)
            {


            }
        }

        private void EndPositionForBookMark()
        {
            try
            {
                SaveBookMarkMessage.Visibility = Visibility.Collapsed;
                SaveEndTime = videoMediaElement.Position;
                if (SaveStartTime.TotalSeconds < SaveEndTime.TotalSeconds)
                {
                    int count = listtable.Count;
                    var item = listtable.ElementAt(count - 1);
                    item.StartTime = item.StartTime;
                    item.EndTime = SaveEndTime.ToString().Split('.')[0];
                    StartTimeStatus = false;
                    listitems.Items.Clear();
                    if (endtimestatus == true)
                    {
                        previewid++;

                        endtimestatus = false;
                        // listtable.Reverse();
                        PlayListTable previewitem = new PlayListTable();
                        previewitem.StartTime = SaveStartTime.ToString();
                        previewitem.EndTime = SaveEndTime.ToString();
                        previewitem.LinkUrl = AppSettings.LinkUrl;
                        previewitem.BookMarkNo = (previewid-1).ToString();
                        previewlist.Add(previewitem);

                    }

                    foreach (PlayListTable itm in listtable)
                    {
                        listitems.Items.Add(itm);
                    }
                    listitems.Items.Cast<PlayListTable>().OrderBy(i => i.BookMarkNo);
                }
                else
                {
                    SaveBookMarkMessage.Text = "Bookmark end time should be greater than bookmark start time";
                    SaveBookMarkMessage.Visibility = Visibility.Visible;
                    //string bookmarkmessage = "Bookmark end time should be greater than bookmark start time";
                    //MessageBoxResult result = MessageBox.Show(bookmarkmessage);
                   
                }
            }
            catch (Exception ex)
            {

            }
        
        }
        #endregion


        void MixVideosPopupPage_Loaded(object sender, RoutedEventArgs e)
        {
            GetBookMarksInBackground();
            StartTimeStatus = false;
            StartPreview = false;
            videotitle.Text = AppSettings.Title;
            videoplaylist();
        }

        private void GetBookMarksInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();
            List<PlayListTable> list = new List<PlayListTable>();
            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {

                                            a.Result = OnlineShow.GetBookMarkDetailsForShow(int.Parse(AppSettings.ShowID));
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            list = (List<PlayListTable>)a.Result;
                                            if (list.Count != 0)
                                            {
                                                foreach (PlayListTable playlist in list)
                                                {

                                                    listitems.Items.Add(playlist);
                                                }
                                                previewlist.AddRange(list);
                                                listtable.AddRange(list);
                                                previewid = list.Count;


                                            }
                                            else
                                            {
                                                SaveBookMarkMessage.Text = "tap on the start and end app icons below to create clicks to be player.";
                                                SaveBookMarkMessage.Visibility = Visibility.Visible;
                                                previewid = list.Count;
                                            }

                                        });
            bwHelper.RunBackgroundWorkers();
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {

                if (AppSettings.LinkUrl != "")
                {
                    AppSettings.YoutubeUri = string.Empty;
                    if (AppSettings.LinkUrl.StartsWith("http://www.dailymotion.com"))
                    {
                        DownloadManagerDailyMotion.dailyDownload(e.Result, dailyQuality.hd720);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://vimeo.com/"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadvideoUrlforVimeoSite(e.Result);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.veoh.com"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetVideoUrlForVeohSite(e.Result);
                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.metacafe.com"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadVideoUrlFromMetacafeSite(e.Result);

                    }
                    else if (AppSettings.LinkUrl.StartsWith("http://www.sevenload.com"))
                    {
                        AppSettings.YoutubeUri = "http://ak.cdn.sevenload.net/slcom-production/cdn/" + AppSettings.LinkUrl.Substring(AppSettings.LinkUrl.LastIndexOf("-") + 1) + "/mobile-h264.main-md.mp4";
                    }
                    else if (AppSettings.LinkUrl.Contains("youtube.com"))
                    {
                        AppSettings.YoutubeUri = DownloadManagerHelper.GethtmlData(e.Result);

                    }
                    else
                    {
                        AppSettings.YoutubeUri = AppSettings.LinkUrl;
                    }
                    youtub();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void imgclose_Tapped(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

        }
        private void SaveForCutVideo_Tapped_1(object sender, EventArgs e)
        {
             int showid=Convert.ToInt32(AppSettings.ShowID);
           //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            if (Constants.Gettileimage == false)
            {
          
                List<ShowList> playlist =Task.Run(async()=>await Constants.connection.Table<ShowList>().Where(i=>i.ShowID==showid).ToListAsync()).Result;
                                             
                var showlist = playlist.FirstOrDefault();
                SaveTileImage.SaveShowlistImage(Constants.TileImageUrl, showlist.Title);
                Constants.Gettileimage =true;
            }
            List<PlayListTable> xquery = Task.Run(async () => await Constants.connection.Table<PlayListTable>().Where(v => v.ShowID == showid).ToListAsync()).Result;
            if (xquery.Count() > 0)
            {
                List<PlayListTable> list = new List<PlayListTable>();
                list.AddRange(xquery);
                foreach (var playlist in list)
                {
                    Constants.connection.DeleteAsync(playlist);
                }
            }
            foreach (var listitem in previewlist)
            {

                DownloadManager.InsertPlaylistTable(TimeSpan.Parse(listitem.StartTime), TimeSpan.Parse(listitem.EndTime), listitem.LinkUrl, int.Parse(AppSettings.ShowID));
            }
            SaveBookMarkMessage.Text = "Video mix successfully saved.";
            SaveBookMarkMessage.Visibility = Visibility.Visible;
        }
        private void PreviewForCutVideo_Tapped_1(object sender, EventArgs e)
        {
            StartPreview = true;
            videoMediaElement.Stop();
            PreviewPlaylistIndex = 0;
            videoplaylist();
        }

        private void StartTime_Tapped_1(object sender, MouseButtonEventArgs e)
        {
            StartpositionForBookmark();
        }

    

        private void EndTime_Tapped_1(object sender, MouseButtonEventArgs e)
        {
            EndPositionForBookMark();

        }

      

        private void Deletebookmarkitem_Click_1(object sender, MouseButtonEventArgs e)
        {
            try
            {

                listitems.Items.Clear();
                listtable.Clear();
                previewlist.Clear();
                previewid = 1;

            }
            catch (Exception ex)
            {

            }
        }

        private void imgBookmarkDelete_Tapped_1(object sender, MouseButtonEventArgs e)
        {
            try
            {
                deletebookmark = true;
            }
            catch (Exception ex)
            {

            }
        }


      

        private void videoMediaElement_PositionChanged_1(object sender, RoutedPropertyChangedEventArgs<TimeSpan> e)
        {

        }

        private void videoMediaElement_MediaStarting_1(object sender, Microsoft.PlayerFramework.MediaPlayerDeferrableEventArgs e)
        {

            if (StartPreview == true)
            {
                videoMediaElement.StartTime = starttime;
                videoMediaElement.EndTime = endtime;
                //videoMediaElement.LivePosition = starttime;
                videoMediaElement.StartupPosition = starttime;
                marker.Time = endtime;
                videoMediaElement.Markers.Add(marker);
                videoMediaElement.MarkerReached += videoMediaElement_MarkerReached;
                markerstatus = false;
            }
        }

        void videoMediaElement_MarkerReached(object sender, Microsoft.PlayerFramework.TimelineMarkerRoutedEventArgs e)
        {
            if (markerstatus == false)
            {
                videoMediaElement.Stop();
                videoplaylist();
                markerstatus = true;
            }
        }

        private void videoMediaElement_RateChanged_1(object sender, Microsoft.PlayerFramework.RateChangedRoutedEventArgs e)
        {

        }

        private void videoMediaElement_MediaEnded_1(object sender, Microsoft.PlayerFramework.MediaPlayerActionEventArgs e)
        {

        }

        private void videoMediaElement_MediaFailed_1(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void goBSave_Click(object sender, EventArgs e)
        {

        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            try
            {

                listitems.Items.Clear();
                listtable.Clear();
                previewlist.Clear();
                previewid = 1;

            }
            catch (Exception ex)
            {

            }
        }

        private void appbarstart_Click_1(object sender, EventArgs e)
        {
            StartpositionForBookmark();
            SaveBookMarkMessage.Visibility = Visibility.Collapsed;
        }

        private void appbariconEnd_Click_1(object sender, EventArgs e)
        {
            EndPositionForBookMark();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {

            if (AppSettings.bcount)
            {
                if (NavigationService.CanGoBack)
                    NavigationService.GoBack();
                //TODO: Use the onBackKeyPress in RatingPopup
                //ratingPopup.close();
            }
            if (previewlist.Count != 0)
            {
                //MessageBoxResult result = MessageBox.Show("are you save This video mix ?","",MessageBoxButton.OKCancel);
                //if (result == MessageBoxResult.OK)
                //{
                //    foreach (var listitem in previewlist)
                //    {

                //        DownloadManager.InsertPlaylistTable(TimeSpan.Parse(listitem.StartTime), TimeSpan.Parse(listitem.EndTime), listitem.LinkUrl, int.Parse(AppSettings.ShowID));
                //    }
                //    MessageBox.Show("your video mix successfully saved");
                //}
            }
            base.OnBackKeyPress(e);
        }

        private void listitems_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (deletebookmark == true)
                {
                    PlayListTable selecteditem =(PlayListTable)(sender as ListBox).SelectedItem;
                    listtable.Remove(selecteditem);
                    var previewitem = previewlist.Where(i => i.BookMarkNo == selecteditem.ID.ToString()).FirstOrDefault();
                    previewlist.Remove(previewitem);
                    deletebookmark = false;
                    listitems.Items.Remove(selecteditem);
                   
                }
            }
            catch (Exception ex)
            {
              
            }
        }
    }
}